import html2canvas from 'html2canvas'

export function copyFields<T extends object, U extends object>(source: T, target: U, createNewObj: boolean = false): U | void {
  if (typeof source !== 'object' || source === null) {
    throw new Error('Source must be a non-null object.')
  }

  if (typeof target !== 'object' || target === null) {
    throw new Error('Target must be a non-null object.')
  }

  if (createNewObj) {
    // 浅拷贝target对象，确保不修改原对象
    const newTarget = { ...target }

    // 遍历source的每个键
    for (const key in source) {
      // 判断source是否是自身属性，而不是原型链上的属性
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        // 判断target对象是否包含该字段
        if (key in target) {
          try {
            // 进行值的复制到新的对象中
            (newTarget as any)[key] = source[key]
          } catch (error) {
            console.error(`Error copying field ${key}:`, error)
          }
        }
      }
    }
    return newTarget
  } else {
    for (const key in source) {
      // 判断source是否是自身属性，而不是原型链上的属性
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        // 判断target对象是否包含该字段
        if (key in target) {
          try {
            // 进行值的复制到新的对象中
            (target as any)[key] = source[key]
          } catch (error) {
            console.error(`Error copying field ${key}:`, error)
          }
        }
      }
    }
  }
}

// 保存图片
export const savePageAsImage = async (el?: HTMLElement, callback?: () => void, fileName = '') => {
  try {
    const canvas = await html2canvas(el || document.body)
    const img = canvas.toDataURL('image/png')
    const imgElement = document.createElement('img')
    imgElement.src = img

    // 创建下载链接
    const a = document.createElement('a')
    a.href = img
    a.download = fileName || '页面截图.png'
    a.click()
  } catch (error) {
    console.error('Error saving page as image:', error)
  } finally {
    if (callback) {
      callback!()
    }
  }
}

// 传入时间，返回当前时间所在月的开始和结束日期
export function getMonthRange(date: Date | string): [string, string] {
  // 处理传入参数，确保是 Date 对象
  const inputDate = (date instanceof Date) ? date : new Date(date)

  // 获取当前日期的年份和月份
  const year = inputDate.getFullYear()
  const month = inputDate.getMonth()

  // 获取当前月份的第一天
  const startDate = new Date(year, month, 1 + 1)

  // 获取当前月份的下一个月的第一天，然后减去 1 毫秒得到当前月份的最后一天
  const endDate = new Date(year, month + 1, 1)
  endDate.setTime(endDate.getTime() - 1)

  // 格式化日期为 YYYY-MM-DD 格式
  const startDateFormatted = startDate.toISOString().split('T')[0]
  const endDateFormatted = endDate.toISOString().split('T')[0]

  // 返回结果数组
  return [startDateFormatted, endDateFormatted]
}
